<template>
  <el-dialog
    v-el-drag-dialog
    title="瓶批单"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <div>
      412
    </div>
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
      <el-form-item label="责任机构" prop="orgName">
        <el-input v-model="userInfo.orgName" disabled />
      </el-form-item>
      <el-form-item label-width="0">
        <el-input v-model="csmText" placeholder="请输入">
          <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户电话" value="csmRgPhone" />
            <el-option label="客户名称" value="csmName" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label-width="0">
        <div>
          <el-button slot="append" class="append-search" @click="search">查询</el-button>
          <el-button slot="append" class="append-search" @click="resetData">重置</el-button>
        </div>
      </el-form-item>
      <el-form-item label="客户" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="电话" prop="contactPhone">
        <el-select v-model="temp.contactPhone">
          <el-option v-for="item in phoneList" :key="item.csmPhone" :value="item.csmPhone" :label="item.csmPhone" />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="csmAddressId">
        <el-select v-model="temp.csmAddressId">
          <el-option v-for="item in csmAddressList" :key="item.csmAddressId" :value="item.csmAddressId" :label="item.csmAddress" />
        </el-select>
      </el-form-item>
      <el-form-item label="批发类型" prop="wsaleType">
        <el-select v-model="temp.wsaleType" placeholder="请选择">
          <el-option
            v-for="item in wsaleTypeBottleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送车辆" prop="truckNo">
        <el-select v-model="temp.truckNo" placeholder="请选择" clearable>
          <el-option
            v-for="item in truckList"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运费" prop="decimalSpare1">
        <el-input v-model="temp.decimalSpare1" :max="100000" @input="temp.decimalSpare1=temp.decimalSpare1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="司机" prop="driver">
        <el-select v-model="temp.driver" multiple placeholder="请选择" clearable>
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员" prop="escortName">
        <el-select v-model="temp.escortName" multiple placeholder="请选择" clearable>
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
      </el-form-item>
      <el-form-item label="商品分类" prop="goodsTypeObj" style="width: 42%;">
        <el-select v-model="temp.goodsTypeObj" value-key="gtId" :loading="$loadingPlugin.getGoodsTypeFn" filterable placeholder="请选择" clearable style="width: 100%;" @change="goodsTypeChange">
          <el-option
            v-for="item in goodsTypeList"
            :key="item.gtId"
            :label="item.gtName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品列表" prop="goodsByTypeObj" style="width: 42%;">
        <el-select v-model="temp.goodsByTypeObj" value-key="goodsId" :loading="$loadingPlugin.getGoodsList" filterable placeholder="请选择" clearable style="width: 100%;" @change="goodsChange">
          <el-option
            v-for="item in goodsByTypeList"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="0" style="width: 2%;">
        <el-button type="primary" size="mini" @click="addGoods">添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      highlight-current-row
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryCsmInfo, queryTruckList, queryDriverList, queryEscortList, goodsTypeQueryList, queryGoodsByType, queryGoodsInfo } from '@/api'
  import { mapGetters } from 'vuex'
  import { accDiv, accMul } from '@/utils/math'

  export default {
    name: 'add-bottle-order',
    data() {
      return {
        visible: false,
        csmText: '',
        qtype: 'csmCode',
        wsaleTypeBottleMap: [{ 'value': 1, 'desc': '预约批发', 'key': 'TYPE1' }, { 'value': 2, 'desc': '上门批发', 'key': 'TYPE2' }],
        csmInfo: undefined,
        phoneList: [],
        csmAddressList: [],
        truckList: [],
        driverList: [],
        escortList: [],
        goodsTypeList: [],
        goodsByTypeList: [],
        temp: {
          csmSearchType: 'csmPhone',
          csmAddressId: '',
          csmName: '',
          csmId: '',
          csmCode: '',
          contactPhone: '',
          wsaleType: 1,
          truckNo: '',
          decimalSpare1: '',
          driver: '',
          escortName: '',
          remark: '',
          goodsTypeObj: undefined,
          goodsByTypeObj: undefined
        },
        selectGoods: undefined,
        selectGoodsPrice: 0, // 商品最新价格
        selectGoodsWeight: 0, // 商品重量
        selectGtFlag: 0, // 业务类型
        selectGdProperty: 0, // 商品属性
        tableData: {
          data: [],
          column: [
            {
              prop: 'goodsName',
              label: '商品'
            },
            {
              prop: 'specName',
              label: '规格型号'
            },
            {
              prop: 'gCount',
              label: '数量',
              align: 'right',
              render: (h, scope) => scope.row._edit ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^-?\d]/g, '').replace(/^-?0+/g, '')} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'gdWeight',
              label: '每瓶重量(kg)',
              align: 'right',
              render: (h, scope) => scope.row._edit && scope.row.pricingMode === 2 ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1')} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'netWeight',
              label: '总重量(吨)',
              align: 'right'
            },
            {
              prop: 'gPrice',
              label: '单价',
              align: 'right'
            },
            {
              prop: 'tReceivable',
              label: '金额',
              align: 'right'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, scope) => {
                return (
                  scope.row._edit ? <div>
                    <el-link type='primary' underline={false} size='mini' onClick={() => this.saveRow(scope)}>
                      保存
                    </el-link>
                    <el-link size='mini' type='danger' underline={false} onClick={() => this.delRow(scope)}>
                      删除
                    </el-link>
                  </div> : <div>
                    <el-link type='primary' underline={false} size='mini' onClick={() => this.editRow(scope)}>
                      编辑
                    </el-link>
                    <el-link size='mini' type='danger' underline={false} onClick={() => this.delRow(scope)}>
                      删除
                    </el-link>
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ])
    },
    watch: {
      'temp.driver': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.temp.driver = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.temp.driver.splice(val.indexOf(0), 1)
        }
        if (this.temp.driver.length === 0) this.temp.driver = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'temp.escortName': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.temp.escortName = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.temp.escortName.splice(val.indexOf(0), 1)
        }
        if (this.temp.escortName.length === 0) this.temp.escortName = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    methods: {
      async open(temp) {
        await Promise.all([this.getTruckList(), this.getDriverList(), this.getEscortList(), this.getGoodsTypeFn()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      // 查询配送车辆列表
      async getTruckList() {
        const res = await queryTruckList()
        console.log('运输车辆', res)
        this.truckList = res.data
      },
      // 查询司机列表
      async getDriverList() {
        const res = await queryDriverList()
        console.log('司机列表', res)
        this.driverList = res.data
      },
      // 查询押运员列表
      async getEscortList() {
        const res = await queryEscortList({})
        console.log('查询押运员列表', res)
        this.escortList = res.data
      },
      // 查询商品分类下拉列表
      async getGoodsTypeFn() {
        const res = await goodsTypeQueryList({
          gtFlag: 3
        })
        console.log('查询商品分类下拉列表', res)
        this.goodsTypeList = res.data
        if (res.data.length > 0) {
          this.temp.goodsTypeObj = res.data[0]
          this.getGoodsList(res.data[0].gtId)
        }
      },
      // 查询
      async search() {
        if (!this.csmText) {
          this.$message.warning('查询条件不能为空!')
          return
        }
        const params = {
          csmStatus: 9, // 查询状态不是已注销的客户
          csmType: 8 // 瓶批客户
        }
        params[this.qtype] = this.csmText
        const res = await queryCsmInfo(params)
        if (!res.data) {
          this.$message.info('此用户不存在')
          return
        }
        if (res.data.csmType !== 8) {
          this.$message.info('此用户不是瓶批用户')
          return
        }
        this.csmInfo = res.data
        console.log('this.csmInfo', this.csmInfo)
        let isChangeCustom = false
        if (this.temp.csmId !== 0) {
          if (this.temp.csmId !== this.csmInfo.csmId) {
            // 说明客户没有改变
            isChangeCustom = true
          }
        }
        this.temp.csmName = this.csmInfo.csmName
        // 电话
        this.phoneList = this.csmInfo.phoneItems.filter(item => item.cpStatus === 2)
        if (this.phoneList.length) {
          this.temp.contactPhone = this.phoneList[0].csmPhone
        }
        this.temp.csmId = this.csmInfo.csmId // 客户id
        this.temp.csmCode = this.csmInfo.csmCode // 客户编号
        this.temp.csmType = this.csmInfo.csmType // 客户类型
        // 地址
        this.csmAddressList = this.csmInfo.addressItems
        if (this.csmAddressList.length) {
          this.temp.csmAddressId = this.csmInfo.addressItems[0].csmAddressId
        }
        if (this.phoneList && this.phoneList.length > 0) {
          if (this.temp.csmSearchType === 'csmPhone') { // 说明电话查找
            this.phoneList.forEach(item => {
              if (item.csmPhone === this.csmText) {
                this.$set(this.temp, 'csmPhone', item.csmPhone)
              }
            })
          } else {
            this.$set(this.temp, 'csmPhone', this.phoneList[0].csmPhone)
          }
        }
        if (this.tableData.data.length !== 0 && isChangeCustom) {
          this.$message.info('客户发生变化对应的区域价格可能发生变化,商品需重新选择')
          // 清空表格商品
          this.$set(this.tableData, 'data', [])
        }
      },
      // 添加商品
      async addGoods() {
        if (!this.temp.goodsTypeObj || !this.temp.goodsByTypeObj) {
          this.$message.warning('请选择商品类别及商品！')
          return
        }
        if (!this.csmInfo) {
          this.$message.warning('请选择客户！')
          return
        }
        console.log('this.tableData.data', this.tableData.data)
        // 查询当前商品详情
        const res = await queryGoodsInfo({
          goodsCode: this.temp.goodsByTypeObj.goodsCode,
          orgSNNo: this.userInfo.orgSNNo,
          csmId: this.temp.csmId,
          csmType: this.temp.csmType
        })
        this.selectGoods = res.data
        this.selectGoodsPrice = res.data.basePrice // 当前商品价格
        this.selectGoodsWeight = res.data.weight // 商品重量
        this.selectGtFlag = res.data.gtFlag
        this.selectGdProperty = res.data.gdProperty
        let tReceivable = 0
        if (this.selectGoods.pricingMode === 1) { // 说明是按包装计价
          tReceivable = this.selectGoods.basePrice.toFixed(2)
        } else if (this.selectGoods.pricingMode === 2) { // 说明是按单位计价
          tReceivable = accMul(this.selectGoods.basePrice, this.selectGoods.weight).toFixed(2)
        }
        if (this.tableData.data.some(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)) {
          const copy = JSON.parse(JSON.stringify(this.tableData.data))
          const match = copy.find(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)
          match.gCount++
          const index = copy.findIndex(item => item.goodsName === this.temp.goodsByTypeObj.goodsName)
          copy.splice(index, 1, match)
          this.$set(this.tableData, 'data', copy)
        } else {
          this.tableData.data.push(
            {
              goodsName: this.selectGoods.goodsName,
              specName: this.temp.goodsByTypeObj.specName,
              gCount: 1,
              gdWeight: this.selectGoods.weight.toFixed(2),
              netWeight: Number(accDiv(this.selectGoods.weight, 1000)).toFixed(5),
              gPrice: this.selectGoods.basePrice,
              tReceivable: tReceivable,
              pricingMode: this.selectGoods.pricingMode
            }
          )
        }
      },
      // 编辑行
      async editRow(scope) {
        this.$set(scope.row, '_edit', true)
      },
      // 保存行
      saveRow(scope) {
        let tReceivable = 0
        this.$set(scope.row, '_edit', false)
        if (scope.row.pricingMode === 1) { // 说明是按包装计价
          tReceivable = accMul(scope.row.gPrice, scope.row.gCount).toFixed(2)
        } else if (scope.row.pricingMode === 2) { // 说明是按单位计价
          tReceivable = accMul(scope.row.gCount, scope.row.gdWeight * scope.row.gPrice).toFixed(2)
        }
        scope.row.tReceivable = tReceivable
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      // 删除行
      delRow(scope) {
        this.tableData.data.splice(scope.$index, 1)
      },
      // 商品类型改变
      async goodsTypeChange(obj) {
        this.temp.goodsByTypeObj = undefined
        this.getGoodsList(obj.gtId)
      },
      // 查询商品列表
      async getGoodsList(gtId) {
        const res = await queryGoodsByType({
          gtId
        })
        console.log('查询商品列表', res)
        this.goodsByTypeList = res.data
      },
      // 商品改变
      async goodsChange(obj) {
        this.temp.goodsByTypeObj = obj
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'gdWeight' || column.property === 'gPrice') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })

        return sums
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (!this.temp.csmName) {
            this.$message.warning('未获取客户名称!')
            return
          }
          // 结束编辑
          if (this.tableData.data.some(item => item._edit)) {
            this.$message.warning('请结束编辑！')
            return
          }
          const matchAddress = this.csmAddressList.find(item => item.csmAddressId === this.temp.csmAddressId)
          const params = {
            orgId: this.csmInfo.orgId,
            orgName: this.csmInfo.orgName,
            orgSNNo: this.csmInfo.orgSNNo,
            csmId: this.csmInfo.csmId,
            csmName: this.csmInfo.csmName,
            csmCode: this.csmInfo.csmCode,
            contactPhone: this.temp.contactPhone,
            contact: this.csmInfo.csmName,
            csmAddressId: matchAddress.csmAddressId,
            csmAddress: matchAddress.csmAddress,
            csmType: this.csmInfo.csmType,
            wsaleFlag: 1,
            decimalSpare1: this.temp.decimalSpare1,
            truckNo2: this.temp.truckNo,
            wsaleType: this.temp.wsaleType,
            truckNo: this.temp.truckNo,
            driver: this.temp.driver,
            escortName: this.temp.escortName,
            remark: this.temp.remark
          }
          const orderWsaleOrderDetailInfoList = this.tableData.data.map(item => {
            return { ...item }
          })
          params.push(orderWsaleOrderDetailInfoList)
          params.goodsDesc = this.temp.goodsByTypeObj.goodsName + '^' + this.selectGoods.basePrice + '^' + 1 // 保存商品描述
          params.goodsCount = this.tableData.data.length
          //       const obj ={
          //         gtId:48,
          //         gtFlag:1,
          //         goodsId:950,
          //         goodsCode:S0648,
          //         goodsName:液化气--w,
          //         gdProperty:1,
          //         gdWeight:0.00,
          //         gPrice:100.00,
          //         gCount:20,
          //         netWeight:0,
          //         tReceivable:2000.00,
          //         specCode:S0336,
          //         specAlias:15KG,
          //         specName:15KG,
          //         pricingMode:1
          //       }
          // ],
          // decimalSpare4:2010.00,
          // tReceivables:2010.00
          console.log('飒飒水水保存')
        })
      },
      // 重置
      resetData() {
        console.log('从之')
      },
      reset() {
        this.csmText = ''
        this.qtype = ''
        this.temp = {
          csmSearchType: 'csmPhone',
          csmName: '',
          csmAddressId: '',
          csmId: '',
          csmCode: '',
          contactPhone: '',
          wsaleType: 1,
          truckNo: '',
          decimalSpare1: '',
          driver: '',
          escortName: '',
          remark: '',
          goodsTypeObj: undefined,
          goodsByTypeObj: undefined
        }
        this.tableData.data = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
